/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, rule, BinaryExpression } from "qvog-dsl";

const SEVERITY = 2;
const DOC_PATH = 'docs/use-isnan-check.md';
const DESCRIPTION = 'Require calls to `isNaN()` when checking for `NaN`';
const operator = /^(?:[<>]|[!=]=)=?$/u;
function isSpecificId(node: ts.Node, name: string): boolean {
    return ts.isIdentifier(node) && node.text === name;
}

function isSpecificMemberAccess(node: ts.Node, objectName: string, propertyName: string): boolean {
    return (ts.isPropertyAccessExpression(node) &&
        ts.isIdentifier(node.expression) && node.expression.text === objectName &&
        ts.isIdentifier(node.name) && node.name.text === propertyName) ||
        (ts.isElementAccessExpression(node) &&
            ts.isIdentifier(node.expression) && node.expression.text === objectName &&
            ts.isStringLiteral(node.argumentExpression) && node.argumentExpression.text === propertyName);
}

function isNaNIdentifier(node: ts.Node): boolean {
    if (ts.isParenthesizedExpression(node)) {
        let express = node.expression;
        if (ts.isBinaryExpression(express)) {
            return isNaNIdentifier(express.right);
        }
        return isNaNIdentifier(express);
    }

    return isSpecificId(node, 'NaN') || isSpecificMemberAccess(node, 'Number', 'NaN');
}

export default rule()
    .match(BinaryExpression)
    .when((node): boolean => {
        const left = node.left;
        const right = node.right;
        return (isNaNIdentifier(left) || isNaNIdentifier(right)) && operator.test(node.operatorToken.getText());
    })
    .report({
        severity: SEVERITY,
        description: DESCRIPTION,
        docPath: DOC_PATH,
    });
